import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select, TreeSelect, Checkbox, Tabs, Tag, Popover, Upload } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, getArrayByValue, getArrayByKey, confirmDelete, download, backUrl } from 'lib/fun'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const Dragger = Upload.Dragger;

// 新建编辑
class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1',   //tab选中
      loading: false,
      tagList: [],
      dicList: [],
      visabled: false,
      rowdata: {},
      projectAttach: [],
      editFileType: "new",
      editFileRowData: {},
      top: false,
      newsType: ""
    }
    this.um = false
  }

  componentDidMount(){
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.setState({
        activeKey: '1',
        projectAttach: [],
        top: false,
        newsType: ""
      });
      this.um&&(this.um.setContent(""))
    }else{
      if(!this.um){
        this.initUeditor(nextProps);
      }
      if(nextProps.type == 'edit'&&!this.props.visible){
        this.um&&(this.um.setContent(nextProps.rowdata.content));
        this.setState({
          top: nextProps.rowdata.top,
          newsType: nextProps.rowdata.newsType
        });
      }
    }
  }

  initUeditor = (nextProps)=>{
    var self = this;
    window.UMEDITOR_CONFIG.toolbar = [
            'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
            'insertorderedlist insertunorderedlist | selectall cleardoc paragraph | fontfamily fontsize' ,
            '| justifyleft justifycenter justifyright justifyjustify |',
            'link unlink | emotion image',
            '| horizontal preview fullscreen', 'drafts',
        ];
    if(document.getElementById('ueditor')){
      var serverPath = '/news/uploadfile';
      this.um = window.UM.getEditor('ueditor', {
        imageUrl: backUrl('/news/uploadfile'),
        imagePath:"",
        lang:/^zh/.test(window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage) ? 'zh-cn' : 'en',
        langPath:window.UMEDITOR_CONFIG.UMEDITOR_HOME_URL + "lang/",
        autoHeight: true,
      });
      if(nextProps&&nextProps.type == 'edit'){
        this.um.ready(function() {
          //设置编辑器的内容
          self.um.setContent(nextProps.rowdata.content);
        });
      }
    }else{
      setTimeout(function(){
        self.initUeditor(nextProps);
      }, 1000);
    }
  }

  handleCommit = () => {
    var self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { type, rowdata  } = self.props;
        console.log(values);
        if(self.props.type == 'edit'){
          values.newsId = rowdata.newsId;
        }
        // values.projectAttach = self.state.projectAttach;
        values.top = values.top?1:0;
        if(values.top){
          values.sort = parseInt(values.sort);
        }
        values.content = this.um.getContent();
        Ajax({
          url: '/news/save',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type, values);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visabled: true,
        editFileType: type,
        editFileRowData: row
      });
    }else{
      this.setState({
        visabled: true,
        editFileType: type
      });
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = _.find(self.state.projectAttach, (item)=>{
        return item.attachUrl == rowdata.attachUrl
      })
      Object.assign(find, rowdata);
    }else{
      rowdata.randomId = parseInt(Math.random()*1000000);
      self.state.projectAttach.push(rowdata);
    }
    self.setState({
      visabled: false,
      editFileRowData: {},
      projectAttach: self.state.projectAttach
    });
  }
  editCancel = ()=>{
    this.setState({
      visabled: false,
      editFileRowData: {}
    });
  }
  doDelete = (rowdata)=>{
    var self = this;
    _.remove(self.state.projectAttach, (item)=>{
      return rowdata.attachId&&item.attachId == rowdata.attachId||item.randomId == rowdata.randomId
    });
    self.setState({
      projectAttach: self.state.projectAttach
    })
  }

  downloadFile = (obj)=>{
    download(`${obj.attachUrl}`);
  }

  checkChange = (e)=>{
    this.setState({
      top: e.target.checked
    });
  }

  newsTypeChange = (key)=>{
    this.setState({
      newsType: key
    })
  }

  renderProject = ()=>{
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    const formItemLayout2 = {
      labelCol: { span: 12 },
      wrapperCol: { span: 12 },
    };
    const { visible, type, projectCate, config, rowdata, common } = this.props;

    return (
    <div>
      <Row gutter={20}>
        <Col span={12}>
          <FormItem {...formItemLayout} label="新闻类型">
            {getFieldDecorator("newsType",{
              initialValue: type == 'edit'?rowdata.newsType+"":"",
              rules: [{
                required: true, message: '请选择新闻类型',
              }]
            })(
              <Select
                size="default"
                disabled={type=='edit'}
                onChange={this.newsTypeChange}
              >
                {
                  (common.newsTypeEn||[]).map(function(obj){
                    return (<Option key={obj.code+""} value={ obj.code+"" }>{ obj.mean }</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>
        {this.state.newsType==2&&(<Col span={12}>
          <FormItem {...formItemLayout} label="是否强提示">
            {getFieldDecorator("notice",{
              initialValue: type == 'edit'?!!rowdata.notice:false,
              valuePropName: 'checked'
            })(
              <Checkbox />
            )}
          </FormItem>
        </Col>)}
        <Col span={12}>
          <FormItem {...formItemLayout} label="新闻标题">
            {getFieldDecorator("title",{
              initialValue: type == 'edit'?rowdata.title:"",
              rules: [{
                required: true, message: '请输入新闻标题',
              }]
            })(
              <Input size="default"/>
            )}
          </FormItem>
        </Col>
        <Col span={12}>
          <FormItem {...formItemLayout} label="是否置顶">
            {getFieldDecorator("top",{
              initialValue: type == 'edit'?rowdata.top:false,
              valuePropName: 'checked'
            })(
              <Checkbox onChange={this.checkChange}/>
            )}
            {this.state.top&&(
              <div className="inner-label" style={{display: 'inline-block',verticalAlign: 'top',width: 266}}>
              <Row>
              <Col span={24}>
                <FormItem {...formItemLayout} label="排序字段">
                  {getFieldDecorator("sort",{
                    initialValue: type == 'edit'?rowdata.sort:"",
                    rules: [{
                      required: true, message: '请输入排序字段',
                    }]
                  })(
                    <Input size="default"/>
                  )}
                </FormItem>
              </Col></Row></div>
            )}
          </FormItem>
        </Col>
        <Col span={12}>
          <FormItem {...formItemLayout} label="新闻标签">
            {getFieldDecorator("tags",{
              initialValue: type == 'edit'?rowdata.tags:"",
            })(
              <Input size="default"/>
            )}
          </FormItem>
        </Col>
        <Col span={12}>
          <FormItem {...formItemLayout} label="新闻备注">
            {getFieldDecorator("remark",{
              initialValue: type == 'edit'?rowdata.remark:"",
            })(
              <Input size="default"/>
            )}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={22} offset={1}>
          <div id="ueditor" style={{height: 240}}></div>
        </Col>
      </Row>
    </div>
    )
  }

  renderProjectAttach = ()=>{
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 18 },
      wrapperCol: { span: 6 },
    };
    const { visible, type } = this.props;
    const { bankCode } = this.props.config;

    const columns = [{
      title: '附件类别',
      dataIndex: 'attachTypeCode',
      render: (text, record) => (<span>{ getNameByCode(this.props.config, 'attachTypeCode', text) }</span>)
    }, {
      title: '附件名称',
      dataIndex: 'attachName'
    }, {
      title: '附件地址',
      dataIndex: 'attachUrl',
      render: (text, record) => {
        return record.projectId?(<a href="javascript:;" title="下载文件" onClick={ this.downloadFile.bind(this, record) }>{ text }</a>):(<span>{ text }</span>)
      }
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (<span><a onClick={this.operate.bind(this, 'edit', record)} href="javascript:;">编辑</a> | <a onClick={this.doDelete.bind(this, record)} href="javascript:;">删除</a></span>)
    }];

    return (
      <div>
        <Table 
          columns={columns}
          dataSource={ this.state.projectAttach }
          rowKey="randomId"
          size="small"
          pagination={false}
        />
        <div style={{textAlign:'center',marginTop:15}}>
          <Button type="dashed" onClick={ this.operate.bind(this, 'new') } style={{ width: '100%' }}>
            <Icon type="plus" /> 添加文件
          </Button>
        </div>
      </div>
    )
  }

  render() {
    const { visible, type, rowdata, projectCate, config } = this.props;
    return (<div>
            <Modal 
              title={ type == 'edit'?"修改新闻":"新建新闻" }
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
              width="920px"
              maskClosable={false}
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  { this.renderProject() }
                {/*
                  <Tabs 
                    defaultActiveKey="1" 
                    activeKey={ this.state.activeKey } 
                    onTabClick={ (key)=>{ this.setState({ activeKey: key }) }}
                  >
                    <TabPane tab="新闻信息" key="1">
                      { this.renderProject() }
                    </TabPane>
                    <TabPane tab="新闻附件" key="2">
                      { this.renderProjectAttach() }
                    </TabPane>
                  </Tabs>
                */}
                </Form>
              </Spin>
            </Modal>
            
            </div>);
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(Form.create()(Edit));
